package handlers

import (
	"net/http"
	"path/filepath"
	"strings"

	"zwai-app/config"
	"zwai-app/middleware"
	"zwai-app/services"
	"zwai-app/util"
)

// RegisterUploadRoutes 注册上传路由
func RegisterUploadRoutes(mux *http.ServeMux, cfg config.Config) {
	mux.HandleFunc("/upload/image", middleware.AuthMiddleware(uploadImageHandler, cfg))
}

// isAllowedImage 检查文件扩展名是否为允许的图片格式
func isAllowedImage(filename string) bool {
	ext := strings.ToLower(filepath.Ext(filename))
	switch ext {
	case ".jpg", ".jpeg", ".png", ".gif", ".bmp":
		return true
	default:
		return false
	}
}

// uploadImageHandler 只接收前端图片流并上传，仅允许 JPG/PNG/GIF/BMP 格式
// 前端请用 multipart/form-data，字段名为 file
func uploadImageHandler(w http.ResponseWriter, r *http.Request) {
	if r.Method != http.MethodPost {
		util.JSONResponse(w, http.StatusMethodNotAllowed, map[string]interface{}{"code": 1, "msg": "只支持 POST 方法"})
		return
	}

	if err := r.ParseMultipartForm(10 << 20); err != nil {
		util.JSONResponse(w, http.StatusBadRequest, map[string]interface{}{"code": 2, "msg": "解析表单失败: " + err.Error()})
		return
	}

	file, header, err := r.FormFile("file")
	if err != nil {
		util.JSONResponse(w, http.StatusBadRequest, map[string]interface{}{"code": 3, "msg": "请上传名为 file 的文件"})
		return
	}
	defer file.Close()

	if !isAllowedImage(header.Filename) {
		util.JSONResponse(w, http.StatusBadRequest, map[string]interface{}{"code": 4, "msg": "仅支持 JPG、JPEG、PNG、GIF、BMP 格式"})
		return
	}

	// 限制整个请求体最大 5 MB
	r.Body = http.MaxBytesReader(w, r.Body, 5<<20)
	if err := r.ParseMultipartForm(5 << 20); err != nil {
		util.JSONResponse(w, http.StatusRequestEntityTooLarge,
			map[string]interface{}{"code": 7, "msg": "上传文件过大，请小于 5MB"},
		)
		return
	}

	// 上传图片
	url, err := services.UploadImage(r.Context(), file, header)
	if err != nil {
		util.JSONResponse(w, http.StatusInternalServerError, map[string]interface{}{"code": 6, "msg": "上传失败: " + err.Error()})
		return
	}

	util.JSONResponse(w, http.StatusOK, map[string]interface{}{
		"code": 0,
		"msg":  "上传成功",
		"data": map[string]string{"url": url},
	})
}
